import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'
import { subscribeWithSelector } from 'zustand/middleware'
import Cookies from 'js-cookie'
import { emitRedirectEvent } from '@/lib/auth-event'
import { loginRedirect } from '@/assets/static'

export interface User {
  id: number
  wecom_id: string
  avatar: string
  name: string
  nickname: string
  email: string
}

interface AuthItem {
  has_admin: boolean
  has_edit: boolean
  has_view: boolean // 是否有 上传面部图像
  sign: string
  name: string
}

interface AuthState {
  token: string | null
  user: User | null
  authList: AuthItem[]
  _hasHydrated: boolean
  setAuthList: (authList: AuthItem[]) => void
  setAuth: (token: string, user: User | null) => void
  clearAuth: () => void
  redirectToLogin: () => void
  setHasHydrated: (state: boolean) => void
}

// 创建一个变量来存储 setHydrated 函数
let storeSetHydrated: ((state: boolean) => void) | null = null

// 创建认证状态存储
export const useAuthStore = create<AuthState>()(
  persist(
    subscribeWithSelector((set) => {
      // 存储 setHydrated 函数的引用
      const setHasHydrated = (state: boolean) => set({ _hasHydrated: state })
      storeSetHydrated = setHasHydrated
      return {
        token: null,
        user: null,
        authList: [],
        _hasHydrated: false,
        setAuthList: (authList) => set({ authList }),
        setHasHydrated,
        setAuth: (token, user) => {
          Cookies.set('auth-token', token, {
            expires: 7,
            sameSite: 'strict',
            secure: process.env.NODE_ENV === 'production',
          })
          set({ token, user })
        },
        clearAuth: () => {
          // 清除 cookie
          Cookies.remove('auth-token')
          set({ token: null, user: null })
        },
        redirectToLogin: () => {
          if (typeof window !== 'undefined') {
            const pathname = window.location.pathname
            emitRedirectEvent({
              path: loginRedirect,
              from: pathname,
            })
          }
        },
      }
    }),
    {
      name: 'auth-storage',
      storage: createJSONStorage(() => localStorage),
      partialize: (state) => ({
        token: state.token,
        user: state.user,
      }), // 只持久化特定字段
      onRehydrateStorage: () => {
        return (state) => {
          if (state && storeSetHydrated) {
            try {
              storeSetHydrated(true)
            } catch (error) {
              console.error('error', error)
            }
          }
        }
      },
    },
  ),
)

// // subscribeWithSelector 中间件可以设置订阅逻辑移到函数中
// const initializeSubscriptions = () => {
//   // 监控 hydration 状态变化
//   console.log('监控 hydration 状态变化', useAuthStore.subscribe)
//   const unsubHydration = useAuthStore.subscribe(
//     (state) => state._hasHydrated,
//     (hasHydrated) => {
//       console.log('Hydration state changed:', hasHydrated)
//     },
//   )

//   // 如果需要，可以返回取消订阅的函数
//   return () => {
//     unsubHydration()
//   }
// }

// // 如果在客户端环境，立即初始化订阅
// if (typeof window !== 'undefined') {
//   initializeSubscriptions()
// }
